import { defineStore } from "pinia";
import { store } from "../utils";
import { useStorage } from "@/utils/auth";

type AdminResult = {
  adminInfo: AdminView;
  tokenInfo: string;
};

const storage = useStorage();

export const useUserStore = defineStore("admin", {
  state: (): AdminResult => ({
    adminInfo: {
      adminId: storage.getAdmin().adminId || 0,
      adminName: storage.getAdmin().adminName || "",
      phone: storage.getAdmin().phone || "",
      statusCode: storage.getAdmin().statusCode || 1
    },
    tokenInfo: storage.getToken() || ""
  }),
  getters: {
    admin: state => state.adminInfo,
    token: state => state.tokenInfo
  },

  actions: {
    setAdmin(admin: AdminView) {
      this.adminInfo = admin;
      storage.saveAdmin(admin);
    },
    setToken(token: string) {
      this.tokenInfo = token;
      storage.saveToken(token);
    },
    clear() {
      this.adminInfo = {
        statusCode: 1,
        phone: "",
        adminName: "",
        adminId: 0
      };
      this.tokenInfo = "";
      storage.clear();
    },
    /** 刷新`token` */
    async handRefreshToken(data) {}
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
